extends CharacterBody2D
class_name Enemy

@onready var enemy_bullet:PackedScene = preload("res://scn/enemy_bullet.tscn")
@onready var enemy_nodes:Array[Node] = $EnemyNodes.get_children()
@onready var enemy_bullet_nodes:Node2D = $"../EnemyBullets"
@onready var timer:Timer = $Timer

# 攻击间隔
var attack_interval: float = 1 / GlobalConstant.ENEMY_ATTACK_SPEED
var enemy_type = GlobalConstant.EnemyType.ENEMY01
var enemy_state = GlobalConstant.EnemyState.STOP
var enemy_hp = 3
var speed = 100

# 移动位置，移动至、撤消位置
var movePosition:Vector2 = Vector2(300,200)
var revokePosition:Vector2 = Vector2(400,50)

func _ready():
	if enemy_type >= len(enemy_nodes):
		return
	var enemyNode:Sprite2D = (enemy_nodes[enemy_type] as Sprite2D)
	enemyNode.visible = true
	await  get_tree().create_timer(2).timeout
	enemy_state = GlobalConstant.EnemyState.PATROL
	timer.timeout.connect(_on_enemy_bullet_attack_timeout)
	
func _physics_process(delta):
	if attack_interval > 0:
		attack_interval -= delta
	enemy_state_handle(delta)
	
	if not enemy_state == GlobalConstant.EnemyState.PATROL:
		velocity = Vector2.ZERO
	move_and_slide()

func enemy_state_handle(delta):
	match enemy_state:
		GlobalConstant.EnemyState.PATROL:
			patrolEnemy(delta)
			pass
		GlobalConstant.EnemyState.ATTACK:
			# 生产子弹
			generateEnemyBullet()
			pass
		GlobalConstant.EnemyState.DESTORY:
			destoryEnemy()
			pass
		GlobalConstant.EnemyState.REVOKE:
			pass
# 敌人入场巡查
func patrolEnemy(delta):
	var pox = position.x
	var poy = position.y
	if pox <= movePosition.x:
		pox = clamp(pox + speed * delta,0,movePosition.x)
	if poy <= movePosition.y:
		poy = clamp(poy + speed * delta,0,movePosition.y)
	if pox >= movePosition.x and poy >= movePosition.y:
		enemy_state == GlobalConstant.EnemyState.STOP
		if timer.is_stopped():
			timer.start(2)
	position = Vector2(pox,poy)

# 销毁敌人
func destoryEnemy():
	queue_free()

func generateEnemyBullet():
	if attack_interval > 0:
		return
	attack_interval = 1 / GlobalConstant.ENEMY_ATTACK_SPEED
	
	var bulletExample = enemy_bullet.instantiate()
	var selfPosition = self.get_global_position()
	bulletExample.position = selfPosition
	enemy_bullet_nodes.add_child(bulletExample)

func _on_enemy_bullet_attack_timeout():
	enemy_state = GlobalConstant.EnemyState.ATTACK
	timer.stop()

# 被攻击特效
func byAttacked():
	var tween = get_tree().create_tween()
	tween.tween_property(self,"modulate:v",1,0.1).from(3)
	enemy_hp = clamp(enemy_hp-1,0,3)
	if enemy_hp<=0:
		enemy_state = GlobalConstant.EnemyState.DESTORY

